//
//  EggTimer.swift.swift
//  EggTimer
//
//  Created by Huan Di on 17/01/2018.
//  Copyright © 2018 DHuan. All rights reserved.
//

import Foundation

protocol EggTimerProtocol {
    func timeRemainOnTimer(_ timer:EggTimer, timeRemaining: TimeInterval)
    func timerHasFinished(_ timer:EggTimer)
}

// cannot declare "static" struct inside of a class?
struct EggTimerActorStatus{
    let enableStart : Bool
    let enableStop : Bool
    let enableReset : Bool
}

class EggTimer {
    
    var delegate: EggTimerProtocol?
    // declare variables for the timer
    var timer: Timer? = nil
    var startTime: Date?
    var duration: TimeInterval = 360
    var elapseTime: TimeInterval = 0
    
    var isStopped : Bool {
        return timer == nil && elapseTime == 0
    }
    
    var isPaused : Bool{
        return timer == nil && elapseTime > 0
    }
    
    func timerAction() {
        guard let startTime = startTime else {
            return
        }
        let secondsRemaining = (duration - elapseTime).rounded()
        
        elapseTime = -startTime.timeIntervalSinceNow
        if secondsRemaining <= 0 {
            resetTimer()
            delegate?.timerHasFinished(self)
        }
        else {
            delegate?.timeRemainOnTimer(self, timeRemaining: secondsRemaining)
        }
    }
    
    func startTimer() {
        startTime = Date()
        elapseTime = 0
        //schedule a timer with block closure
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {(timer_) -> Void in
            self.timerAction()
        })
        timerAction()
    }
    func resumeTimer() {
        startTime = Date(timeIntervalSinceNow: -elapseTime)
        
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {(timer_) -> Void in
            self.timerAction()
        })
        timerAction()
    }
    func stopTimer() {
        timer?.invalidate()
        timer = nil
        timerAction()
    }
    func resetTimer() {
        timer?.invalidate()
        timer = nil
        startTime = nil
        duration = 360
        elapseTime = 0

        timerAction()
    }

}


